package util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {
	/**
	 * jdbc的静态工具类
	 * @author Administrator
	 *
	 */

		private DBUtil(){}
		
		//驱动类
		private static String className;
		//连接数据库的url
		private static String url;
		//数据库的用户
		private static String username;
		//数据库的密码
		private static String password;
		
		/**
		 * 在静态块中注册驱动
		 */
		static{
			Properties pro = new Properties();
			try {
				//读取资源文件
				pro.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
				
				//通过键获取值
				System.out.println(pro.getProperty("jdbc.driver"));
				System.out.println(pro.getProperty("jdbc.url"));
				System.out.println(pro.getProperty("jdbc.username"));
				System.out.println(pro.getProperty("jdbc.password"));
				
				className = pro.getProperty("jdbc.driver");
				url = pro.getProperty("jdbc.url");
				username = pro.getProperty("jdbc.username");
				password = pro.getProperty("jdbc.password");
				
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			
			try {
				Class.forName(className);
				System.out.println("驱动加载成功！");
			} catch (ClassNotFoundException e) {
				System.out.println("驱动加载失败！");
			}
		}
		/**
		 * 获取数据库连接：创建Connection对象
		 */
		public static Connection getConnection(){
			Connection conn = null;
			try {
				conn = DriverManager.getConnection(url, username, password);
				System.out.println("连接数据库成功！");
			} catch (SQLException e) {
				System.out.println("连接数据库失败！");
			}
			return conn;
		}
		/**
		 * 释放资源
		 */
		public static void close(Connection conn,Statement stmt,ResultSet rs){
			try {
				if(rs != null)
					rs.close();
				if(stmt != null)
					stmt.close();
				if(conn != null)
					conn.close();
				System.out.println("资源释放成功！");
			} catch (SQLException e) {
				System.out.println("资源释放失败！");
			}
		}
}
